package com.example.mypra1.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.clj.memoryspinner.MemorySpinner;
import com.example.mypra1.DreamActivity;
import com.example.mypra1.HomeActivity;
import com.example.mypra1.LoginActivity;
import com.example.mypra1.MainActivity;
import com.example.mypra1.MoreActivity;
import com.example.mypra1.R;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页模块
 */
public class MainFragment1 extends Fragment {

    private Context mContext;
    private View rootView;
    private TextView more;
    private ImageButton iv_dream;
    private ViewGroup mContentView;
    private TextView yi;
    private TextView ji;
    private TextView summary,color,health,xz,love,money,number,work,total;
    private String sat;//星座
    private MemorySpinner memorySpinner;
    private Handler handler=new Handler(){//操作UI,将请求获取的每日宜数据忌渲染到UI

        @Override
        public void handleMessage(@NonNull Message msg) {
            Map<String,Object>map = (Map<String, Object>) msg.obj;
            yi.setText(map.get("yi").toString());//宜
            ji.setText(map.get("ji").toString());//忌
        }
    };
    private Handler handler2=new Handler(){//操作UI,将请求获取的星座运势数据渲染到UI

        @Override
        public void handleMessage(@NonNull Message msg) {
            Map<String,Object>map = (Map<String, Object>) msg.obj;
            summary.setText(map.get("summary").toString());//运势概述
            color.setText(map.get("color").toString());//幸运色
            health.setText(map.get("health").toString());//健康
            xz.setText(map.get("xz").toString());//当前用户选择的星座(默认为用户注册时的星座)
            love.setText(map.get("love").toString());//爱情
            money.setText(map.get("money").toString());//财运
            number.setText(map.get("number").toString());//幸运指数
            work.setText(map.get("work").toString());//工作
            total.setText(map.get("total").toString());//综合
        }
    };

    public static MainFragment1 newInstance() {
        Bundle args = new Bundle();
        MainFragment1 fragment = new MainFragment1();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.main_fragment1, container, false);
        }
        iv_dream = rootView.findViewById(R.id.dream);
        iv_dream.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getApplicationContext(), DreamActivity.class);
                startActivity(intent);
            }
        });
        yi = rootView.findViewById(R.id.yi);
        ji = rootView.findViewById(R.id.ji);
        more = rootView.findViewById(R.id.more);
        //从sharedPreference中取用当前用户的星座
        SharedPreferences pref = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
        sat = pref.getString("constellation","金牛座");
        color = rootView.findViewById(R.id.color);
        health = rootView.findViewById(R.id.health);
        money = rootView.findViewById(R.id.money);
        work = rootView.findViewById(R.id.work);
        number = rootView.findViewById(R.id.number);
        xz = rootView.findViewById(R.id.xz);
        total = rootView.findViewById(R.id.total);
        love = rootView.findViewById(R.id.love);
        summary = rootView.findViewById(R.id.summary);
        memorySpinner = rootView.findViewById(R.id.ms);
        ArrayList<String>list = new ArrayList<>(Arrays.asList("白羊座","金牛座","双子座","巨蟹座","狮子座","处女座",
                "天枰座","天蝎座","射手座","摩羯座","水瓶座","双鱼座"));
        memorySpinner.setData(null,list);
        memorySpinner.setSelection(list.indexOf(sat));
        memorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //用户点击下拉框选择其它星座时触发
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sat = list.get(i);
                getYS();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        //发送网络请求，获取数据
        getYJ();
        getYS();
        //跳转至更多界面
        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext.getApplicationContext(), MoreActivity.class);
                startActivity(intent);
            }
        });
    return rootView;
    }

    private void getYJ(){//请求获取每日宜忌
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String date = dateFormat.format(new Date());
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://v.juhe.cn/laohuangli/d?date="+date+"&key=21f118446eafbd3101fbbf6c3523f0f5")
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                Log.d("res",res);
                                try {
                                    JSONObject jsonObject1 = new JSONObject(res);
                                    JSONObject jsonObject = jsonObject1.getJSONObject("result");
                                    String yi = jsonObject.getString("yi");
                                    String ji = jsonObject.getString("ji");
                                    Map<String,String>map = new HashMap<>();
                                    map.put("yi",yi);
                                    map.put("ji",ji);
                                    Message message = new Message();
                                    message.obj = map;
                                    handler.sendMessage(message);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void getYS(){//请求星座运势
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String date = dateFormat.format(new Date());
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://web.juhe.cn/constellation/getAll?consName="+sat+"&type=today&key=70a442015077d1f7a27eec861c7228bc")
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            Log.d("resp",response.toString());
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                try {
                                    JSONObject jsonObject = new JSONObject(res);
                                    Map<String,String>map = new HashMap<>();
                                    map.put("color",jsonObject.getString("color"));
                                    map.put("number",jsonObject.getString("number"));
                                    map.put("health",jsonObject.getString("health"));
                                    map.put("money",jsonObject.getString("money"));
                                    map.put("love",jsonObject.getString("love"));
                                    map.put("xz",jsonObject.getString("QFriend"));
                                    map.put("work",jsonObject.getString("work"));
                                    map.put("total",jsonObject.getString("all"));
                                    map.put("summary",jsonObject.getString("summary"));
                                    Message message = new Message();
                                    message.obj = map;
                                    handler2.sendMessage(message);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Log.d("resp",response.toString());
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
